import json
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import Supply, Category


# 物料视图
# Create your views here.
@xframe_options_exempt
def index(request):
    categories = Category.objects.filter(is_delete=0).order_by("-create_time").all()
    return render(request, "supply/index.html", {"categories":categories})


def supply_list(request):
    result = {"status": 1, "msg": "操作失败！"}
    data = request.GET
    try:
        page = data.get("page", 1)
        limit = data.get("limit", 5)
        search = data.get("search")
        category_id = data.get("category_id")

        supplies = Supply.objects.filter(is_delete=0)
        if search and search != "":
            supplies = supplies.filter(name__icontains=search)
        if category_id and category_id != "" and int(category_id) != 0:
            supplies = supplies.filter(category_id=int(category_id))
        supply_count = supplies.count()
        paginator = Paginator(supplies.order_by("-create_time"), limit)     # 每页多少条数据
        try:
            supplies = paginator.page(page)        # 返回 page（页数）的数据
        except PageNotAnInteger:
            supplies = paginator.page(1)           # 第一页
        except EmptyPage:
            supplies = paginator.page(paginator.num_pages)  # 最后一页

        data_list = []
        for i in range(len(supplies)):
            data_list.append({
                "No": i+1,
                "id": supplies[i].id,
                "name": supplies[i].name,
                "number": supplies[i].number,
                "category": supplies[i].category.name,
                "remark": supplies[i].remark,
                "create_time": str(supplies[i].create_time).split(".")[0],
            })

        result["data"] = data_list
        result["data_count"] = supply_count
        result["status"] = 0    # layui parseData status=0 才认为是成功
        result["msg"] = "物料列表查询成功！"
    except Exception as e:
        print(e)
    return JsonResponse(result)


@xframe_options_exempt
def supply_add(request):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            name = data.get("name")
            remark = data.get("remark")
            category_id = data.get("category_id")

            sp_exist_count = Supply.objects.filter(name=name).count()
            if sp_exist_count > 0:
                result["msg"] = "该物料名称已存在！"
                return JsonResponse(result)
            cg_exist = Category.objects.filter(id=int(category_id)).first()
            if not cg_exist:
                result["msg"] = "物料分类不存在！"
                return JsonResponse(result)

            new_supply = Supply.objects.create(name=name, remark=remark, category_id=cg_exist.id)
            new_supply.save()
            result["status"] = 1
            result["msg"] = "物料添加成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        categories = Category.objects.filter(is_delete=0).order_by("-create_time").all()
        return render(request, "supply/add.html", {"categories": categories})


@xframe_options_exempt
def supply_edit(request, sp_id):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            name = data.get("name")
            remark = data.get("remark")
            category_id = data.get("category_id")

            supply = Supply.objects.filter(id=int(sp_id), is_delete=0).first()
            if not supply:
                result["msg"] = "请确认物料是否正确！"
                return JsonResponse(result)

            if supply.category_id != int(category_id):
                cg_exist = Category.objects.filter(id=int(category_id)).first()
                if not cg_exist:
                    result["msg"] = "物料分类不存在！"
                    return JsonResponse(result)
                supply.category_id = cg_exist.id
            if supply.name != name:
                name_exist = Supply.objects.filter(~Q(id=int(sp_id)), name=name, is_delete=0).first()
                if name_exist:
                    result["msg"] = "该名称已存在!"
                    return JsonResponse(result)
                supply.name = name
            if supply.remark != remark:
                supply.remark = remark
            supply.save()
            result["status"] = 1
            result["msg"] = "物料信息更新成功!"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        supply = Supply.objects.filter(id=int(sp_id), is_delete=0).first()
        categories = Category.objects.filter(is_delete=0).order_by("-create_time").all()
        return render(request, "supply/edit.html", {'supply': supply, "categories": categories})


def supply_del(request, sp_id):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "DELETE":
        try:
            supply = Supply.objects.filter(id=int(sp_id), is_delete=0).first()
            if not supply:
                result["msg"] = "请确认物料是否正确！"
                return JsonResponse(result)
            supply.is_delete = 1
            supply.save()
            result["status"] = 1
            result["msg"] = "物料删除成功!"
        except Exception as e:
            print(e)
    return JsonResponse(result)

